﻿using DocumentFormat.OpenXml.Office2010.Excel;
using Domain.Material_Management;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Material_Management;
using MES.Server.API.Dto.Material_Management.OutPut;
using ReturnValue;

namespace MES.Server.API.Application.Handler.Material_Management
{
    public class GetMaterialAskHander : IRequestHandler<GetMaterialAskCommand, ApiPaging<GetMaterialAskOutPut>>
    {
        private readonly IRepository<MaterialAskModel> materialAskRepo;
        private readonly IRepository<ProductMaterialsModel> productMaterialsRepo;
        public GetMaterialAskHander(IRepository<MaterialAskModel> materialAskRepo, IRepository<ProductMaterialsModel> productMaterialsRepo)
        {
            this.materialAskRepo = materialAskRepo;
            this.productMaterialsRepo = productMaterialsRepo;
        }
        /// <summary>
        /// 物料申请查询
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiPaging<GetMaterialAskOutPut>> Handle(GetMaterialAskCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<GetMaterialAskOutPut>();
            var materialAsk = materialAskRepo.GetAll().Where(x => x.IsDel == false);
            var productMaterials = productMaterialsRepo.GetAll().Where(x => x.IsDel == false);
            var linq = from a in materialAsk
                       join b in productMaterials on a.ProductMaterialsId equals b.Id into ab
                       from b in ab.DefaultIfEmpty()
                       select new GetMaterialAskOutPut
                       {

                            Id=a.Id,
                           MaterialAskCode = a.MaterialAskCode,
                            ProductMaterialsId=b.Id,
                            ProductMaterialsName=b.ProductMaterialsName,
                            MaterialAskCount=a.MaterialAskCount,
                            MaterialAskUnit=a.MaterialAskUnit,
                            MaterialAskDesc=a.MaterialAskDesc,  
                            MaterialAskStatus=a.MaterialAskStatus,
                            CreateTime=a.CreateTime ,
                            CreaterPeople=a.CreaterPeople,
                            UpdateTime=a.UpdateTime,

                       };
            result.TotalPage = linq.OrderByDescending(x => x.CreateTime).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            result.Totalcount = linq.Count();
            result.Code = StatusCode.Success;
            return Task.FromResult(result);
        }
    }
}
